<?php

namespace App\Http\Controllers\Admin\Census;

use App\Http\Controllers\BaseController;
use App\Services\Tools\CommonService;
use Carbon\Carbon;
use Illuminate\Http\Request;    //引用http请求类
use App\Exceptions\BasicException;  //引入框架异常处理类
use Illuminate\Support\Facades\Hash;    //引入hash
use App\Services\Cache\AdminCacheService;   //admin缓存
use App\Services\Tools\JwtService;    //引入JWT服务
use App\Services\Tools\FileService;   //引入文件处理类
use App\Response\Response;
use App\Models\MainDB\GiveGiftDay;
use Illuminate\Support\Facades\Redis;

class CensusController extends BaseController {

    /**
     * @api {post} /census/list 数据统计列表
     * @apiVersion 0.1.0
     * @apiName 数据统计列表
     * @apiGroup 数据统计
     *
     * @apiParam {string} start_time   开始时间,非必传
     * @apiParam {string} end_time     结束时间，非必传
     * @apiParam {string} keyword     关键字，非必传
     * @apiParam {string} grade     等级，非必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
          "list": [
                  {
                      "money（流水金额）": "0.14",
                      "from_unixtime(pay_time,'%Y%m%d')（日期）": "20200714",
                    }
                 ],
          "meta": {
               "page（页数）": 1,
               "limit（每页数量）": 100,
              "next（下一页）": null,
              "total（总数）": 2
          },
          "header": {
             "total_flowing_water（平台总流水）": 285091530106,
              "total_registered_users"（总注册人数）: 95486,
              "total_recharge（总充值流水）": "90.14",
              "total_withdraw（总提现金额）": "1600.00"
             }
         }
    }
     *
     */
    public function censusList(Request $request) {

        $start_time = $request->input('start_time', '');
        $end_time = $request->input('start_time', '');
        $keyword = $request->input('keyword', '');
        $grade = $request->input('grade', 0);

        $time = CommonService::transTime($start_time, $end_time);
        $where = [];
        $start_time = $time['start_at'];
        $end_time = $time['end_at'];

        //平台总流水
        $total_give_gift_day = app('repo_give_gift_day')->TotalGiveGiftDay();
        $total_give_gift = app('repo_give_gift')->TotalGiveGift();
        $total_flowing_water = $total_give_gift_day + $total_give_gift;

        //获取用户注册总数
        $search_time = [$start_time, $end_time];
        $where[] = [function ($query) use ($search_time) {
            $query->whereBetween('register_time', $search_time);
        }];
        $total_registered_users = app('repo_user')->totalRegisteredUsers($where);
        $param = [
            'start_time' => $start_time,
            'end_time' => $end_time,
            'keyword' => $keyword,
            'grade' => $grade,
        ];
        //总充值
        $total_recharge = app('repo_user_recharge')->userRecharge($param);
        //获取充值列表
        $recharge_list = app('repo_user_recharge')->rechargeList($param);

        //用户总提现
        $total_withdraw = app('repo_user_withdraw')->userWithdraw($param);

        $ext = [
            'total_flowing_water' => $total_flowing_water,
            'total_registered_users' => $total_registered_users,
            'total_recharge' => $total_recharge,
            'total_withdraw' => $total_withdraw,
        ];
        return Response::sendList($recharge_list, [], $ext, $code = 200);
    }

    /**
     * @api {post} /census/data_census   新版数据统计
     * @apiVersion 0.1.0
     * @apiName 新版数据统计
     * @apiGroup 数据统计
     * @apiSuccessExample 成功响应
        {
            "code": 200,
            "data": {
                "total_registered_users（平台总注册人数）": 95503,
                "today_register_user（平台今日注册人数）": 1,
                "today_total_recharge（今日充值金额）": 0,
                "total_recharge（充值总金额）": "100000120.14",
                "total_withdraw（提现总金额）": 0,
                "total_fish_money（小猫钓鱼消费总额）": 28974,
                "hour_recharge（每小时充值金额数据）": [
                    "12.00"
                ],
                "hour_withdraw（每小时提现金额数据）": [
                    "200.00"
                ],
                "one（低于一千人百分比）": "100%",
                "two（一千到五千百分比）": "0%",
                "three（五千到一万百分比）": "0%",
                "four（一万以上百分比）": "0%",
                "china（中国个地区用户分布）": [
                    {
                    "count_user_ip（用户数量）": 96,
                    "address（地区名称）": "浙江省"
                    }
                ]
            }
        }
     *
     */
    public   function  dataCensus(){
            //平台总注册人数
             $total_registered_users = app('repo_user')->totalRegisteredUsers();
             //平台今日注册人数
             $today_start = Carbon::today()->timestamp;
             $today_end = Carbon::tomorrow()->timestamp;
             $search_time =[$today_start,$today_end];
             $where[] = [function($query) use ($search_time){
                 $query->whereBetween('register_time',$search_time);
             }];
             $today_register_user = app('repo_user')->totalRegisteredUsers($where);
            //今日充值金额
            $param = [
                'start_time' => $today_start,
                'end_time' => $today_end,
            ];
            $today_total_recharge = app('repo_user_recharge')->userRecharge($param);
            //用户总充值金额
            $start_time = '';
            $end_time = '';
            $time = CommonService::transTime($start_time,$end_time);
            $param = [
                'start_time' => $time['start_at'],
                'end_time' =>  $time['end_at'],
            ];
            $total_recharge = app('repo_user_recharge')->userRecharge($param);
            //用户总提现
            $total_withdraw = app('repo_user_withdraw')->userWithdraw($param);
            //小猫钓鱼总消费金额
            $all_total_gold=app('repo_gold_price')->allTotalGold();
            $total_fish_money =round( $all_total_gold/100,2);
            //充值每小时充值金额数据
            $hour_second =3600;
            $hour_recharge =[];
            //每小时提现金额数据
            $hour_withdraw =[];
            for ($x=0; $x<=24; $x++) {
                $end_time =$hour_second*$x +$today_start;
                $start_time =$end_time -$hour_second;
                $param = [
                    'start_time' => $start_time,
                    'end_time' => $end_time,
                ];
                $today_total_recharge = app('repo_user_recharge')->userRecharge($param);
                $hour_recharge[$x] =$today_total_recharge;
                $total_withdraw = app('repo_user_withdraw')->userWithdraw($param);
                $hour_withdraw[$x] =$total_withdraw;
            }
            //先获取缓存数据china
            $china =json_decode(Redis::get('ip:user:allip'),true);
            if ($china){
                $max_id =app('repo_config')->queryConfig('MAX_USER_ID_IP');
                if ($max_id){
                    $max_id =$max_id->value;
                }else{
                    $max_id =0;
                }
            }else{
                $china =CommonService::China();
                $max_id =0;
            }
            $list=app('repo_user_device')->DeviceList($max_id);
            $item=array();
            if ($list){
                $max_id = max(array_column($list,'id'));
                foreach ($list as  $key=>&$value){
                    //todo 这个地方要换一下ak 还有数量的限制
                    $url = "http://api.map.baidu.com/location/ip?ak=oX5Fm3DDBnfaUZEeS7lmxAdwxySbNEki&ip=".$value['ip'];
                    $res = json_decode(file_get_contents($url),true);
                    if ($res['status']==0){
                        $address =$res['content']['address_detail']['province'];
                    }else{
                        $address =$res['message'];
                    }
                    $value['address'] =$address;
                    unset($value['id']);
                    unset($value['ip']);
                }
                $max_user_ip =app('repo_config')->queryConfig('MAX_USER_ID_IP');
                if ($max_user_ip){
                    if ($max_user_ip->value !=$max_id){
                        $where_config[] =['key','MAX_USER_ID_IP'];
                        $param =[
                            'value'=>$max_id
                        ];
                        app('repo_config')->saveConfig($where_config,$param);
                    }
                }else{
                    $param =[
                        'value'=>$max_id,
                        'key'=>'MAX_USER_ID_IP',
                        'name'=>'获取ip的最大id',
                    ];
                    app('repo_config')->addConfig($param);
                }
            }
            $data = array_merge($china,$list);
            if ($data){
                foreach($data as $k=>$v){
                    if(!isset($item[$v['address']])){
                        $item[$v['address']]=$v;
                    }else{
                        $item[$v['address']]['count_user_ip']+=$v['count_user_ip'];
                    }
                }
            }
            //四个段的百分比
            $one =0;
            $two =0;
            $three =0;
            $four =0;
            //获取某个段的百分比
            if ($item){
                foreach (array_values($item) as $key=>$val){
                    if ($val['count_user_ip'] <=1000){
                        $one+=1;
                    }elseif ($val['count_user_ip']>1000 && $val['count_user_ip']<=5000){
                        $two+=1;
                    }elseif ($val['count_user_ip']>5000 && $val['count_user_ip']<=10000){
                        $three+=1;
                    }else{
                        $four+=1;
                    }
                }
            }
            $one =100*round($one/count($item),2).'%';
            $two =100* round($two/count($item),2).'%';
            $three =100* round($three/count($item),2).'%';
            $four =100* round($four/count($item),2).'%';
            Redis::setex('ip:user:allip' , 86400000 , json_encode(array_values($item)));
            $all_data =[
                //平台总注册人数
                'total_registered_users'=>$total_registered_users,
                //平台今日注册人数
                'today_register_user'=>$today_register_user,
                //今日充值金额
                'today_total_recharge'=>$today_total_recharge,
                //用户总充值金额
                'total_recharge'=>$total_recharge,
                //用户总提现金额
                'total_withdraw'=>$total_withdraw,
                //小猫钓鱼消费总额
                'total_fish_money'=>$total_fish_money,
                //每小时充值金额数据
                'hour_recharge'=>$hour_recharge,
                //每小时提现金额数据
                'hour_withdraw'=>$hour_withdraw,
                //注册地百分比
                'one'=>$one,
                'two'=>$two,
                'three'=>$three,
                'four'=>$four,
                //中国各地区用户数量
                'china'=>array_values($item)
            ];
            return Response::sendData($all_data);
    }


}
